<script setup>
import {User, Lock, CircleCheck} from '@element-plus/icons-vue'
import {markRaw, onMounted, reactive, ref} from 'vue'
import {getLoginCaptchaAPI, getUserInfoByIdAPI, userLoginAPI, userRegisterService} from "@/api/user.js";
import {useRouter} from "vue-router";
import {useTokenStore} from '@/stores/token.js'
import {ElMessage} from "element-plus";
import {useUserInfoStore} from "@/stores/userInfo.js";
//控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false)
const registerData = ref({
  loginId: '',
  loginPwd: '',
  reLoginPwd: ''
})
const loginData = ref({
  loginId: 'admin',
  loginPwd: '123456',
  captcha: ''
})
const router = useRouter()
const tokenStore = useTokenStore()
const userStore = useUserInfoStore()
const captchaSvg = ref('')
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("请再次确认密码"));
  } else if (value !== registerData.value.password) {
    callback(new Error("请确保两次输入密码一致"));
  } else {
    callback()
  }
}
const rules = {
  loginId: [
    {required: true, message: "请输入学号/工号", trigger: 'blur'},
    {min: 5, max: 16, message: '长度必须为5到16位', trigger: 'blur'}
  ],
  loginPwd: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 5, max: 16, message: '长度必须为5到16位', trigger: 'blur'}
  ],
  captcha: [
    {validator: checkRePassword, trigger: 'blur'}
  ]
}
const register = async () => {
  let result = await userRegisterService(registerData.value)
  ElMessage(result.msg ? result.msg : "注册成功");
}
const login = async () => {
  let result = await userLoginAPI(loginData.value);
  if(result.status === 200 && result.data.code === 0) {
    ElMessage.success("登录成功")
    tokenStore.setToken(result.headers?.['authentication'])
    const result1 = await getUserInfoByIdAPI(result.data.data.id)
    userStore.setInfo(result1.data.data)
    router.push('/')
  }  else {
    ElMessage.warning(result.data?.msg)
    result.data?.msg === '验证码错误' && await getLoginCaptcha()
  }
}
const clearRegisterData = () => {
  registerData.value = {
    username: '',
    password: '',
    rePassword: ''
  }
}
/**
 * 获取登录验证码 返回一个 svg 格式的图片 可使用 v-html 直接渲染
 * @returns {Promise<void>}
 */
const getLoginCaptcha = async () => {
  const result = await getLoginCaptchaAPI()
  captchaSvg.value = result.data
}
onMounted(async () => {
  const result = await getLoginCaptchaAPI()
  captchaSvg.value = result.data
})
</script>

<template>
  <el-row class="login-page">
    <el-col :span="6" :offset="9" class="form">
      <h1 style="display: flex; justify-content: center;">河北经贸大学校友网</h1>
      <!-- 注册表单-->
      <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
        <el-form-item size="small">
          <h2 style="color: #4f5559;">注册</h2>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                    v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                    v-model="registerData.rePassword"></el-input>
        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="register">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterData()">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>
      <!-- 登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else :model="loginData" :rules="rules">
        <el-form-item size="small">
          <h2 style="color: #4f5559;">登录</h2>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入学号/工号" v-model="loginData.loginId"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                    v-model="loginData.loginPwd"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="CircleCheck" type="password" placeholder="请输入验证码"
                    v-model="loginData.captcha"></el-input>
          <div @click="getLoginCaptcha" class="captcha-container" v-html="captchaSvg"></div>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
        </el-form-item>
        <el-form-item class="flex" style="justify-content: flex-end">
          <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterData()">
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    :deep(.el-form-item--small .el-form-item__content) {
      display: flex;
      justify-content: center;
    }

    :deep(.el-form-item__content) {
      display: flex;
      flex-wrap: nowrap;
    }

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;

      :deep(.el-form-item__content) {
        justify-content: flex-end;
      }
    }

    .captcha-container {
      width: 150px;
      height: 38px;
      display: flex;
      border: 1px solid var(--el-border-color);
      cursor: pointer;
      border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
      box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
    }
  }
}
</style>